package controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import models.Node;

import com.et.mvc.JsonView;
import com.et.mvc.View;

public class NodeController extends ApplicationController{
	/**
	 * get nodes, if the 'id' parameter equals 0 then load the first level nodes,
	 * otherwise load the children nodes
	 * @param id the parent node id value
	 * @return the tree required node json format
	 * @throws Exception
	 */
	public View getNodes(int id) throws Exception{
		List<Node> nodes = null;
		
		if (id == 0){	// return the first level nodes
			nodes = Node.findAll(Node.class, "parentId=0 or parentId is null", null);
		} else {	// return the children nodes
			nodes = Node.findAll(Node.class, "parentId=?", new Object[]{id});
		}
		
		List<Map<String,Object>> items = new ArrayList<Map<String,Object>>();
		for(Node node: nodes){
			Map<String,Object> item = new HashMap<String,Object>();
			item.put("id", node.id);
			item.put("text", node.name);
			
			// the node has children, 
			// set the state to 'closed' so the node can asynchronous load children nodes 
			if (node.hasChildren()){
				item.put("state", "closed");
			}
			items.add(item);
		}

		return new JsonView(items);
	}
}
